/**
 * 分词客户端
 */

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "segmentationcli.h"

int cli_connect() {
    int s;
    struct sockaddr_in addr;
    char buffer[256];
    if((s = socket(AF_INET,SOCK_STREAM,0))<0){
        perror("connect socket error");
        abort();
    }
    /* 填写sockaddr_in结构*/
    bzero(&addr,sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port=htons(SERVER_DEFAULT_PORT);
    addr.sin_addr.s_addr = inet_addr(SERVER_DEFUALT_HOST);
    /* 尝试连线*/
    if(connect(s,&addr,sizeof(addr))<0){
        perror("connect error");
        exit(1);
    }
    return s;
}

//写入指令
int cli_send(int fd, msg* m) {
    char* buf = (&m);
    int count = m->len + 8;
    ssize_t nwritten, totlen = 0;
    while(totlen != count) {
        nwritten = write(fd,buf,count-totlen);
        if (nwritten == 0) return totlen;
        if (nwritten == -1) return -1;
        totlen += nwritten;
        buf += nwritten;
    }
    return totlen;
}